package com.gui.juc.cas;

import com.gui.utils.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

@Slf4j
public class CasABADemo2 {

    public static void main(String[] args) {

        AtomicStampedReference<BigDecimal> atomicReference = new AtomicStampedReference<>(new BigDecimal("10"), 0);

        Thread t1 = new Thread(() -> {
            BigDecimal reference1 = atomicReference.getReference();
            int stamp1 = atomicReference.getStamp();
            boolean result = atomicReference.compareAndSet(reference1, reference1.subtract(new BigDecimal("1")), stamp1, stamp1 + 1);
            log.debug("第一次CAS：{}", result);
            int stamp2 = atomicReference.getStamp();
            Sleeper.sleep(2);
            BigDecimal reference2 = atomicReference.getReference();
            log.debug("版本号：{}，{}", stamp2, atomicReference.getStamp());
            boolean result2 = atomicReference.compareAndSet(reference2, reference2.subtract(new BigDecimal("1")), stamp2, stamp2 + 1);
            log.debug("第二次CAS：{}", result2);

        }, "t1");

        Thread t2 = new Thread(() -> {
            Sleeper.sleep(1);
            BigDecimal reference = atomicReference.getReference();
            int stamp = atomicReference.getStamp();
            boolean result = atomicReference.compareAndSet(reference, reference.add(new BigDecimal("1")), stamp, stamp + 1);
            log.warn("第一次CAS：{}", result);

        }, "t2");
        t1.start();
        t2.start();

        Sleeper.sleep(4);
        log.debug("最终结果：{}, {}", atomicReference.getReference(), atomicReference.getStamp());
    }
}
